<template>
    <div class="Business">
        <Form ref="formData" :model="formData" :rules="formRules" :label-width="100">
            <Row>
                <Col :xs="24" :md="12" :xl="6">
                    <FormItem label="持卡人（旧）" class="item-disabled">
                        <Input clearable v-model="oldData.oldCardholder" disabled/>
                    </FormItem>
                    <!--                    <FormItem label="持卡人（新）" prop="newCardholder">-->
                    <!--                        <Input clearable v-model="formData.newCardholder" placeholder :disabled="isApprove || isApproved"/>-->
                    <!--                    </FormItem>-->
                    <FormItem label="持卡人（新）" prop="newName">
                        <Select v-model="formData.newCardholder"
                                placeholder="请选择主/共借人"
                                :label-in-value="true"
                                :disabled="isFormDisabled"
                        >
                            <Option v-for="(item,index) in personList" :key="index" :label="item.custName"
                                    :value="item.custName">{{item.custName}}
                            </Option>
                        </Select>
                        <!--                        <Input clearable v-model="formData.newCardholder" placeholder :disabled="isApprove || isApproved" />-->
                    </FormItem>
                </Col>
                <Col :xs="24" :md="12" :xl="6">
                    <FormItem label="还款银行（旧）" class="item-disabled">
                        <Select v-model="oldData.oldBank" placeholder="请选择还款银行" disabled>
                            <Option v-for="(item,index) in dataDict.repaymentBankDict" :key="index" :value="item.value">
                                {{ item.title }}
                            </Option>
                        </Select>
                    </FormItem>
                    <FormItem label="还款银行（新）" prop="newBank">
                        <Select v-model="formData.newBank" placeholder="请选择还款银行" :disabled="isFormDisabled">
                            <Option v-for="(item,index) in dataDict.repaymentBankDict" :key="index" :value="item.value">
                                {{ item.title }}
                            </Option>
                        </Select>
                    </FormItem>
                </Col>
                <Col :xs="24" :md="12" :xl="6">
                    <!--                    <FormItem label="分支行（旧）" class="item-disabled">-->
                    <!--                        <Input clearable v-model="oldData.bankBranch" disabled />-->
                    <!--                    </FormItem>-->
                    <PlaceCascade
                        class="item-disabled"
                        label="分支行（旧）"
                        value="bankBranch"
                        :form="oldData"
                        :isDetailAddress="false"
                        :isDisabled="true"
                        :location="initLoadData"
                    />
                    <!--                    <FormItem label="分支行（新）" prop="newBranchBank">-->
                    <!--                        <Input clearable v-model="formData.newBranchBank" placeholder :disabled="isApprove || isApproved" />-->

                    <!--                    </FormItem>-->
                    <PlaceCascade
                        class="item-disabled"
                        label="分支行（新）"
                        value="branchBank"
                        :form="formData"
                        :isDetailAddress="false"
                        :isDisabled="isFormDisabled"
                        :location="initLoadData"
                    />
                </Col>
                <Col :xs="24" :md="12" :xl="6">
                    <FormItem label="银行账号（旧）" class="item-disabled">
                        <Input clearable v-model="oldData.oldBankAccount" disabled/>
                    </FormItem>

                    <FormItem label="银行账号（新）" prop="newBankAccount">
                        <Input clearable v-model="formData.newBankAccount" placeholder :disabled="isFormDisabled"/>
                    </FormItem>
                </Col>
            </Row>

            <Row>
                <!-- <Col :xs="12">
                    <FormItem label="上传身份证:" required>
                        <Button type="primary" @click="openUploadModal('idCard')">上传身份证</Button>
                    </FormItem>
                </Col> -->
                <!-- <Col :xs="12">
                    <FormItem label="上传身份证正面">
                        <fileUpload :modal="true" @afterUpload="messageUpload" @deleteFile="deleteFile" :disabled="isApprove || isApproved" />
                    </FormItem>
                </Col>
                <Col :xs="12">
                    <FormItem label="上传身份证反面">
                        <fileUpload :modal="true" @afterUpload="messageUpload" @deleteFile="deleteFile" :disabled="isApprove || isApproved" />
                    </FormItem>
                </Col>-->
                <Col :xs="24" :md="12" :xl="6">
                    <FormItem label="证件号码" prop="certNo">
                        <Input clearable v-model="formData.certNo" :disabled="isFormDisabled"/>
                    </FormItem>
                </Col>
                <Col :xs="24" :md="12">
                    <FormItem label="有效期止" prop="date">
                        <!-- <Input :value="oldData.certStartDate+ ' 到 ' + oldData.certEndDate" :disabled="isApprove || isApproved" /> -->
                        <DatePicker
                            @on-change="changeCertDate"
                            v-model="formData.certEndDate"
                            format="yyyy-MM-dd"
                            type="date"
                        :disabled="isFormDisabled || formData.isLongTerm"
                        ></DatePicker>
                        <Checkbox style="right: 10px" :disabled="isFormDisabled || (formData.changeType === 'other')"
                                  @on-change="changeEndDate"
                                  v-model="formData.isLongTerm"
                                  type="logo-twitter" label="长期">
                            <span>长期</span>
                        </Checkbox>
                    </FormItem>
                </Col>
            </Row>
<!--            <div style="height:20px"></div>-->
            <Row>
                <!-- <Col :xs="12">
                    <FormItem label="上传银行卡正面">
                        <fileUpload :modal="true" @afterUpload="messageUpload" @deleteFile="deleteFile" :disabled="isApprove || isApproved" />
                    </FormItem>
                </Col>
                <Col :xs="12">
                    <FormItem label="上传银行卡反面">
                        <fileUpload :modal="true" @afterUpload="messageUpload" @deleteFile="deleteFile" :disabled="isApprove || isApproved" />
                    </FormItem>
                </Col>-->
            </Row>
            <Row>
                <!-- TODO:（二维码） -->
            </Row>
            <Row>
                <!-- TODO: 获取划款授权书 -->
                <!-- <Col :xs="24">
                    <FormItem label="签署授权书">
                        <Input type="text" v-model="formData.time" />
                    </FormItem>
                </Col>-->
            </Row>
            <!--            <RadioGroup v-model="formData.signSite">-->
            <!--                <Radio label="线上"></Radio>-->
            <!--                <Radio label="线下"></Radio>-->
            <!--            </RadioGroup>-->
            <!--            <Row>-->
            <!--                <Col :xs="24">-->
            <!--                    <FormItem label="短信验证码" prop="note" v-if="this.formData.signSite==='线上'">-->
            <!--                        <Input type="text" v-model="formData.vc"/>-->
            <!--                        <Button type="primary" @click="verify">发送验证码</Button>-->
            <!--                        <Button type="primary" @click="sign">签约</Button>-->
            <!--                    </FormItem>-->
            <!--                </Col>-->
            <!--            </Row>-->

            <Row>
                <Col :xs="24">
                    <FormItem label="简述原因" prop="remarks">
                        <Input class="remarks-width" type="textarea" v-model="formData.remarks" :disabled="isFormDisabled"/>
                    </FormItem>
                </Col>
                <Col :xs="12">
                    <FormItem label="上传银行卡:" required>
                        <Button type="primary" @click="openUploadModal('bankCard')">上传银行卡</Button>
                    </FormItem>
                </Col>
                    <!--二维码展示-->
                    <Modal v-model="smallProgramAble"
                    >
                        <div style="text-align: center" v-if="binary">
                            <img id="qrcode" :src="'data:image/jpg;base64,'+binary">
                            <p style="font-size: 13px;">
                                <Icon type="ios-alert" color="red">
                                </Icon>&nbsp;请扫描二维码进行认证（有效时间:30分钟）
                            </p>
                        </div>
                    </Modal>
            </Row>
        </Form>
        <UploadFileModal
            ref="uploadFileModal"
            :modal="isUploadFileModalOpen"
            @closeModal="closeModal"
            :param="fileParams"
            @asyncSaveFileFn="asyncSaveFileFn"
            :isPreview="isFormDisabled"
        />
    </div>
</template>
<script>
    import {
        findBankCardDetail,
        findContractPerson,
        findOldBankInfo,
        refresh,
        sign,
        verify,
        getOCRBankInfo
    } from "_p/basic/api/contract/post-loan-info-change";
    import PlaceCascade from "_p/basic/pages/contract/common/PlaceCascade";
    import {verifyErrorToView} from "_p/basic/assets/contract/js/utils";
    import UploadFileModal from "_p/basic/pages/contract/common/uploadFileModal/uploadFileModal";
    import {getLocation} from "_p/basic/api/contract/common/common";

    export default {
    components: {UploadFileModal, PlaceCascade},
    props: {
        dataDict: {
            type: Object,
            required: true
        },
        isApprove: {
            type: Boolean,
            require: true
        },
        //是否 审批完成
        isApproved: {
            type: Boolean,
            required: true
        },
        isReadOnly: {
            type: Boolean,
            default: false
        },
        //对象参数包含：合同号码、角色类型
        Obj: {
            type: Object,
            required: true
        },
        pageParams: {
            type: Object,
            required: true
        }
    },
    data() {
        const validateDate = (rule, value, callback) => {
            if (!value[0] || !value[1])
                callback(new Error('请输入有效期'));
            callback();
        };
        return {
            smallProgramAble:false,
            binary:"",
            caseNo: "",
            personList:{},
            initLoadData: [],
            isUploadFileModalOpen: false,
            fileParams: {},
            showForm: {
                type: "",
                phone: false,
                address: false
            },
            oldData: {},

            formData: {
                certEndDateLabel: "",
                custName: "",
                oldBranchBank: "",
                oldBankAccount: "",
                oldBank: "",
                oldCardholder: "",
                oldCity: "",
                oldProvince: "",
                newCity: "",
                newProvince: "",
                branchBank: [],
                newBankAccount: "",
                newBank: "",
                newCardholder: "",
                signSite: "线上",
                chlCd: "",
                verification: true,
                msgid: "",
                tel: "",
                cardNo: "",
                vc: "",
                certEndDate: "",
                body: {

                    tel: "",
                    cardNo: "",
                }
            },
            formRules: {
                /*newBankAccount: [{required: true, message: "请输入银行账号", trigger: "change"}],
                branchBank: [{required: true, type: 'array', message: "请输入分支行", trigger: "change"}],
                newBank: [{required: true, message: "请选择还款银行", trigger: "change"}],
                newCardholder: [{required: true, message: "请输入持卡人", trigger: "change"}],
                certNo: [{required: true, message: "请输入证件号码", trigger: "change"}],
                date: [
                    {required: true, type: 'array', message: "请输入有效期", trigger: "change"},
                    {validator: validateDate, message: '请输入有效期', trigger: 'change'}
                ],*/
            },
            certDate: [],
        };
    },
    computed: {
        isFormDisabled(){
            return this.isApprove || this.isApproved || this.isReadOnly
        }
    },
    watch: {},
    created() {
    },
    mounted() {
        this.init();
    },
    methods: {
        init() {
            if (this.pageParams)
                this.getBasicInfo(this.pageParams);
            this.findContractPerson(this.pageParams);
            // this.formData = Object.assign({}, this.formData, this.pageParams);
            this.getInitData();
            console.log(this.pageParams,"s1sdsa")

        },
        //主共借人列表
        findContractPerson(v) {
            if(!v) return;
            findContractPerson(v).then(res => {
                if (res.code === "0000") {
                    this.personList = res.data;
                    return true;
                }
            }).catch(e => {
                this.$emit("closeSpin");
            });
        },
        getBasicInfo(data) {
            if (!data) return;
            if(!this.isApproved) {
                findOldBankInfo(data).then(res => {
                    if (res.code === "0000" && res.data) {
                        const {province, city} = res.data
                        //province    旧分支行省份
                        // city    旧分支行城市
                        console.log("old info", res.data);
                        this.formData.certNo = res.data.certNo;
                        this.oldData.oldBank = res.data.bankCode
                        this.oldData.oldCardholder = res.data.accountName;
                        this.oldData.oldBranchBank = res.data.bankBranch
                        this.oldData.oldBankAccount = res.data.accountNo;
                        this.oldData.oldCity = res.data.city;
                        this.oldData.oldProvince = res.data.province;
                        // this.oldData.custName = res.data.custName
                        // this.oldData.startDate = res.data.startDate
                        this.certDate = [res.data.certStartDate,res.data.certEndDate];
                        console.log(this.certDate,"this.certDate")
                        if(province !=null && city != null){
                            // this.oldData.bankBranch = province && city ? [province, city] : []
                            this.oldData.bankBranch = [province, city];
                            console.log("地址信息",this.oldData.bankBranch)
                        }
                        if (this.formData.date == null) {
                            this.formData.date = this.certDate;
                        }
                        this.oldData = Object.assign({}, this.oldData, res.data);

                    }
                });
            }

            findBankCardDetail(data).then(res => {
                if (res.code === "0000" && res.data) {
                    var obj = JSON.stringify(res.data);
                    let d = JSON.parse(obj);
                    this.$emit('baseInfo',d)
                    console.log("new info", res.data);
                    let branchBank = ['', ''];
                    const {caseNo, certStartDate, certEndDate, province, city, oldProvince, oldCity} = res.data;
                    this.caseNo = caseNo;
                    this.formData.newCardholder = res.data.newCardholder;
                    this.formData.certEndDate = certEndDate;
                    this.formData.date =  [certStartDate, certEndDate];
                    console.log("formate.data日期",this.formData.date)
                    if (province)
                        branchBank[0] = province
                    if (city)
                        branchBank[1] = city
                    this.formData = Object.assign({}, this.formData, res.data, {
                        date: [certStartDate, certEndDate],
                        branchBank
                    });
                    if (this.isApproved) {
                        this.oldData = Object.assign({}, this.oldData, res.data, {date: [certStartDate, certEndDate]});
                        this.oldData.bankBranch = oldProvince && oldCity ? [oldProvince, oldCity] : []
                    }
                    if (res.data.certEndDate == "9999-12-31"){
                        this.formData.certEndDate = '长期';
                        this.formData.isLongTerm = true;
                    }
                }
            });
        },

        /*
         * formData 数据验证 验证通过后 将数据传回父级处理  (保存/提交/审核 通用)
         * @param {String} funcName 回传给父级的方法 (注意父级需要传方法)
         * @param {Object} [data]   父级带来的数据
         */
        // formValidate(funcName, data) {
        //     if (!funcName) return;

        //     this.$refs.formData.validate(valid => {
        //         if (valid) {
        //             let d = Object.assign({}, data, this.formData, this.oldData, this.Obj);

        //             this.$emit(funcName, d);
        //         } else {
        //             this.$Message.error("验证不通过!");
        //             this.$emit("closeSpin");
        //             verifyErrorToView(this.$refs.formData.fields);
        //         }
        //     });
        // },
        changeCertDate(date) {
            if (date === '9999-12-31'){
                this.formData.certEndDateLabel = '长期';
            }
            console.log(date,"s211w120s1203")
        },
        messageUpload(uploadInfo) {
            console.log(uploadInfo);
            this.$Message.info("上传文件" + JSON.stringify(uploadInfo));
        },
        deleteFile(fileInfo) {
            console.log(fileInfo);
            this.$Message.info("删除文件" + JSON.stringify(fileInfo));
        },
        /*
           * formData 数据验证 验证通过后 将数据传回父级处理  (保存/提交/审核 通用)
           * @param {String} funcName 回传给父级的方法 (注意父级需要传方法)
           * @param {Object} [data]   父级带来的数据
           */
        formValidate(funcName, data) {
            if (!funcName) return;
            this.parentFuncName = funcName;
            this.$refs.uploadFileModal.formValidate('asyncSaveFileFn', data)
        },
        // 文件上传成功后会触发的方法
        asyncSaveFileFn(data) {
            console.log('ggggggggggggg, 上传成功', data);

            this.$refs.formData.validate(valid => {
                if (valid) {
                    if (Array.isArray(this.formData.branchBank) && this.formData.branchBank.length > 0) {
                        this.formData.province = this.formData.branchBank[0];
                        this.formData.city = this.formData.branchBank[1]
                    }
                    if (this.formData.date == null) {
                        console.log("his.formData.date",this.formData.date)
                    }
                    if (this.formData.isLongTerm == true){
                        this.formData.certEndDate = "";
                    }
                    this.formData.newProvince = this.formData.branchBank[0];
                    this.formData.newCity = this.formData.branchBank[1];
                    if (this.pageParams.id) {
                        this.formData.id = this.pageParams.id
                    }
                    if (this.pageParams.processStatus) {
                        this.formData.processStatus = this.pageParams.processStatus
                    }

                    let d = Object.assign({}, data, this.formData, this.oldData, this.Obj);
                    if (this.formData.certEndDate == null || this.formData.certEndDate == ''){
                        d.certEndDate = null;
                    }else {
                        d.certEndDate = this.formData.certEndDate;
                    }
                    console.log("重置后的数据1",d)
                    console.log("重置后的数据3",this.formData)
                    console.log("重置后的数据2",data)
                    this.$emit(this.parentFuncName, d)

                    // this.$emit(funcName, d);
                } else {
                    this.$Message.error("验证不通过!");
                    this.$emit("closeSpin");
                    verifyErrorToView(this.$refs.formData.fields);
                }
            });
        },
        // fileParams 上传文件的配置参数
        openUploadModal(type) {
            if (this.pageParams.caseNo || this.Obj.caseNo){
                if (type === "bankCard") {
                    this.fileParams = {
                        belongNo: this.Obj.contractNo,
                        busiNo: this.pageParams.caseNo || 'bankCard',
                        busiType: 'bankCard',
                        busiData: {},
                        busiNodes: 'bankCard' //业务节点
                    }
                }
            }else {
                    this.$Modal.warning({
                        title: "警告",
                        content: "请先保存业务数据！"
                    });
                    return;
                }

            this.isUploadFileModalOpen = true;
            console.log("页面数据x`x",this.pageParams);
            getOCRBankInfo(this.pageParams).then(res => {
                if (res.code == "0000") {
                    console.log("识别的数据",res.data)
                    if (res.data == null) return;
                    this.formData.newName =  res.data.newName;
                    this.formData.newBankAccount =  res.data.newBankAccount;
                    // this.formData.certEndDate =  res.data.certEndDate;
                    if(res.data.certNo != null && res.data.certNo != ''){
                        this.formData.certNo =  res.data.certNo;
                    }else {
                        this.$Message.error("申请文件未识别出证件号")
                    }
                    console.log("ocr识别结果",res)
                    console.log("formData结果",this.formData)
                }
                // this.initLoadData.push(...res.data);
            });
        },
        verify() {
            this.formData.tel = this.oldData.contactNo
            this.formData.cardNo = this.oldData.certNo
            console.log(" this.formData.tel", this.formData.tel, this.formData.cardNo, this.showForm.phone, this.oldData.certNo)
            console.log("this.formData", this.formData)
            verify(this.formData).then(res => {
                if (res.code === "0000" && res.data) {
                    console.log("res.data", res.data)
                    this.formData.verification = false;

                }
            });
        },

        sign() {

            if (this.formData.verification) {
                this.$Message.success("请先发送验证码");
                return
            }
            sign(this.formData).then(res => {
                console.log("sign")
                if (res.code === "0000" && res.data) {
                    console.log("res.data", res.data)
                }
            });
        },

        closeModal() {
            // 获取文件长度
            let l = this.$refs.uploadFileModal.getFileList()
            console.log(' 文件长度为1：', l);

            this.isUploadFileModalOpen = false;
        },
        getInitData() {
            let param = {
                level: "1",
                upperCode: "1"
            };
                getLocation(param).then(res => {
                if (res.code == "0000") {
                    res.data.forEach(item => {
                        // 表明是否是父节点
                        if (item.isParent) {
                            item.loading = false;
                            item.children = [];
                        }
                    });
                }
                this.initLoadData.push(...res.data);
            });
        },
        refresh(data){
            this.smallProgramAble = true;
            refresh(data).then(res => {
                if (res.code === '0000') {
                    this.$Message.success("刷新成功");
                    this.refreshTime = res.data.activeTime;
                    this.binary = res.data.code;
                }
            })
        },
        changeEndDate() {
            if (this.formData.isLongTerm) {
                this.required = false;
                this.formData.certEndDate = "长期";
            } else {
                this.required = true;
                this.formData.certEndDate = null;
            }
        }
        // getProductListS(val) {
        //     console.log("获取val的label和value", val)
        //     this.formData.certNo = val.value;
        //     this.formData.custName = val.label;
        // },
        }
    };
</script>
<style lang="less" scoped>
.item-disabled {
    margin-bottom: 0;
    /deep/ .ivu-form-item {
        margin-bottom: 0;
        //max-width: 250px;
    }
    .ivu-cascader-rel {
        display: inline-block;
        width: 100%;
        position: relative;
        max-width: 250px;
    }

}

.type-box {
    display: flex;
    flex-flow: row;
}

.item-title {
    text-align: center;
}

.change-bank-card-detial .remarks-width {
    min-width: calc(50% + 200px);
}
@media screen and (min-width: 1200px) {
    .change-bank-card-detial .remarks-width {
        min-width: calc(75% + 225px);
    }
}

</style>
